package com.hakgc.rent.web.servlet;

import com.alibaba.fastjson.JSON;
import com.hakgc.rent.dto.Result;
import com.hakgc.rent.entity.District;
import com.hakgc.rent.service.DistrictService;
import com.hakgc.rent.service.impl.DistrictServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 访问区县列表页面的Servlet
 * @author Xing.Jiejian
 * @date 2020/11/9
 */
@WebServlet(name = "AddDistrictServlet",urlPatterns = "/rent/district/add")
public class AddDistrictServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收表单数据
        String name = request.getParameter("districtName");
        // 调用业务方法新增区县
        DistrictService districtService = new DistrictServiceImpl();
        District district = new District(name);

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 根据业务方法结果进行不同的响应信息
        if (districtService.addDistrict(district)){
            out.println(JSON.toJSONString(Result.SUCCESS()));
        }else{
            out.println(JSON.toJSONString(new Result<>("区县保存失败，请重新操作！")));
        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收表单数据
        String name = request.getParameter("name");
        // 调用业务方法新增区县
        DistrictService districtService = new DistrictServiceImpl();
        District district = new District(name);

        // 根据业务方法结果进行不同的响应信息
        if (districtService.addDistrict(district)){
            // 保存成功
            // 提示保存成功，并且重新跳转到列表页
            // 重定向的路径，是客户端发起请求的路径，所以如果使用"/"必须添加项目根目录
            response.sendRedirect(request.getContextPath()+"/rent/districts");
        }else{
            // 新增失败
            // 回到表单页，并且提示错误信息
            request.setAttribute("errorMsg","区县保存失败，请重新操作！");
            // 请求的数据同样可以放入request作用域转发回表单页
            request.getRequestDispatcher("/rent/district.jsp").forward(request,response);
        }
    }
}
